/**
 * 折线图-归一处理
 */
var lineChartNormal = {
  /**
   * 初始化
   */
  init: function () {
    this.state = {
      rainData: [], // 所有的降雨量数据
      proData: [], // 所有的产量数据
      renderRainData: [], // 最终渲染图表用的降雨量数据
      renderProData: [], // 最终渲染图表用的产量数据
      years: [1994, 2016], // X 轴数据
      crops: [], // 所有的 crops
      crop: "", // 当前图表对应的 crop，初始是 crops[0]
      states: [], // 所有的 State_Name
      state: "", // 当前图表对应的 state，初始是 states[0]
      xScale: null, // X 轴比例尺， 设置悬浮框需要
      minValue: 0,
      maxValue: 0,
    }
    this.getData();
  },
  /**
   * 获取数据
   */
  getData: function () {
    var self = this;
    d3.csv('data/new_rain.csv', function (error, data) {
      if (error) {
        console.error(error);
      }
      self.state.rainData = data;
    })
    d3.csv('data/crop_production.csv', function (error, data) {
      if (error) {
        console.error(error);
      }
      self.state.proData = data.filter(function (d) {
        return d.Production // 去掉空值脏数据
      })
      self.render();
    })
  },
  /**
   * 渲染图表
   */
  render: function () {
    this.renderCrops();
    this.renderStates();
    this.filterData();
  },
  // 渲染 crops
  renderCrops: function () {
    var data = this.state.proData;
    var crops = [];
    var cropsSelectDom = "";
    data.forEach(function (d) {
      if (crops.indexOf(d.Crop.trim()) === -1) {
        crops.push(d.Crop.trim())
      }
    })
    this.state.crops = crops;
    this.state.crop = crops[0];
    crops.forEach(function (d) {
      cropsSelectDom += "<option>" + d.trim() + "</option>"
    })
    $('.crops-list-normal').html(cropsSelectDom)
  },
  // 渲染 state_name
  renderStates: function () {
    var data = this.state.proData;
    var states = [];
    var stateSelectDom = "";
    data.forEach(function (d) {
      if (states.indexOf(d.State_Name.trim()) === -1) {
        states.push(d.State_Name.trim())
      }
    })
    this.state.states = states;
    this.state.state = states[0];
    states.forEach(function (d) {
      stateSelectDom += "<option>" + d.trim() + "</option>"
    })
    $('.states-list-normal').html(stateSelectDom)
  },
  /**
   * 绑定图表事件
   */
  bindEvent: function () {
    var xScale = this.state.xScale;
    var years = this.state.years;
    var renderProData = this.state.renderProData;
    var renderRainData = this.state.renderRainData;
    var self = this;
    $('.crops-list-normal').off().on('change', function () {
      var crop = $('.crops-list-normal').val();
      self.state.crop = crop;
      self.filterData();
    })
    $('.states-list-normal').off().on('change', function () {
      var state = $('.states-list-normal').val();
      self.state.state = state;
      self.filterData();
    })

    d3.select('.line-chart-normal').on('mousemove', function () {
      var maxValue = self.state.maxValue;
      var minValue = self.state.minValue;

      var x = document.querySelector('.line-chart-normal').getBoundingClientRect().x;
      var event = d3.event;
      var top = d3.event.pageY;
      var left = d3.event.pageX;

      var partX = left - x; // 移动进图表的水平距离

      	var emYear = Math.floor(xScale.invert(partX)) <= years[0] ? years[0] : Math.floor(xScale.invert(partX)) - 2;
// debugger
				var pro = renderProData.filter(function(d) {
					return parseInt(d.Crop_Year, 10) === parseInt(emYear, 10);
				})
				var rain = renderRainData.filter(function (d) {
					return parseInt(d.YEAR, 10) === parseInt(emYear, 10);
				})

      var option = {
        el: '.auto-tooltip',
        location: {
          x: left,
          y: top
        },
        data: [{
          name: '年份',
          value: emYear ? emYear : '未知年份'
        }, {
          name: '产量Min-Max标准值',
          value: pro.length === 1 ? self.normalData(pro[0].Production, maxValue, minValue).toFixed(2) || 0 : '暂无数据'
        }, {
          name: '降雨量Min-Max标准值',
          value: rain.length === 1 ? self.normalData(rain[0].ANNUAL, maxValue, minValue).toFixed(2) || 0 : '暂无数据'
        }]
      }
      var el = self.tooltip(option)
      el.show()
    })
    .on('mouseout', function () {
      $('.auto-tooltip').hide()
    })
  },
  tooltip: function (option) {
    var el = option.el
    var location = option.location
    var data = option.data
    var text = ''
    for (var i = 0, length = data.length; i < length; i++) {
      if (length == 1) {
        text += data[i].name + '<br>' + data[i].value
      } else {
        text += data[i].name + '：' + data[i].value + '<br>'
      }
    }
    $(el).html(text)
    var globalWidth = $('body').outerWidth()
    var globalHeight = $('body').outerHeight()
    var elWidth = $(el).outerWidth()
    var elHeight = $(el).outerHeight()
    location.x = location.x - elWidth / 2
    location.y = location.y - elHeight - 10
    if (location.x + elWidth / 2 > globalWidth) {
      location.x = globalWidth - elWidth
    }
    $(el).css({
      left: location.x,
      top: location.y
    })
    return $(el)
  },
  /**
   * 过滤数据
   */
  filterData: function () {
    // 过滤 产量数据
    var proData = this.state.proData;
    var crop = this.state.crop;
    var state = this.state.state;

    var renderProData = [];
    var years = []
    // 按照 crop 和 state 筛选
    var csData = proData.filter(function (d) {
      return d.Crop.trim() === crop && d.State_Name.trim() === state;
    })
    // 按照 Crop_Year 排序，使 X 轴年份递增
    csData.sort(function (a, b) {
      return parseInt(a.Crop_Year, 10) - parseInt(b.Crop_Year, 10);
    })
    // 按照 Crop_Year 去重
    csData.forEach(function (d) {
      if (years.indexOf(parseInt(d.Crop_Year, 10)) === -1) {
        years.push(parseInt(d.Crop_Year, 10));
        renderProData.push(d)
      }
    })
    // 过滤降雨量数据
    var rainData = this.state.rainData;
    // 按照地区名字过滤 和 年份过滤
    var renderRainData = rainData.filter(function (d) {
      return d.SUBDIVISION.toLowerCase() === state.toLowerCase() && years.indexOf(parseInt(d.YEAR, 10)) !== -1
    })
    renderRainData.sort(function (a, b) {
      return parseInt(a.YEAR, 10) - parseInt(b.YEAR, 10);
    })
    this.state.renderProData = renderProData;
    this.state.renderRainData = renderRainData;
    // 将两组数据用于绘图
    this.renderChart();
  },
  /**
   * 数据归一处理
   * 采用： Min-Max标准化
   * 新数据 = （原数据 - 最小值） / （最大值 - 最小值）
   */
  normalData: function (x, max, min) {
    return (x - min) / (max - min);
  },
  /**
   * 绘制折线图
   */
  renderChart: function () {
    var renderProData = this.state.renderProData;
    var renderRainData = this.state.renderRainData;
    var years = this.state.years;

    // console.log(renderProData, renderRainData, years);

    $('.line-chart-normal').html('');
    var colors = ['green', '#4cc6ec']; // 两个填充色
    var width = 1170;
    var height = 500;
    var svg = d3.select('.line-chart-normal')
    var padding = {
      top: 20,
      right: 100,
      bottom: 100,
      left: 100
    };

    var maxPro = d3.max(renderProData, function (d) {
      return parseFloat(d.Production, 10)
    })
    var maxRain = d3.max(renderRainData, function (d) {
      return parseFloat(d.ANNUAL)
    })
    var minPro = d3.min(renderProData, function (d) {
      return parseFloat(d.Production, 10)
    })
    var minRain = d3.min(renderRainData, function (d) {
      return parseFloat(d.ANNUAL)
    })

    var maxValue = Math.max(maxPro, maxRain);
    var minValue = Math.min(minPro, minRain);
    this.state.maxValue = maxValue;
    this.state.minValue = minValue;

    var xScale = d3.scale.linear()
      .domain([years[0], years[1]])
      .range([0, width - padding.left - padding.right]);

    this.state.xScale = xScale;
    var self = this;
    var yScale = d3.scale.linear()
      .domain([0, 1]) // 最大值为 1
      .range([height - padding.top - padding.bottom, 0]);

    //创建产量的直线生成器
    var proLinePath = d3.svg.line()
      .x(function (d) {
        return xScale(parseInt(d.Crop_Year, 10));
      })
      .y(function (d) {
        return yScale(self.normalData(parseFloat(d.Production, 10), maxValue, minValue));
      })
      // .interpolate("basis");

    //创建降雨的直线生成器
    var rainLinePath = d3.svg.line()
      .x(function (d) {
        return xScale(parseInt(d.YEAR, 10));
      })
      .y(function (d) {
        return yScale(self.normalData(parseFloat(d.ANNUAL, 10), maxValue, minValue));
      })
      // .interpolate("basis");

    //添加路径 -- 产量
    svg.append("path")
      .data([renderProData])
      .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
      .attr("d", function (d) {
        return proLinePath(d);
      })
      .attr("fill", "none")
      .attr("stroke-width", 3)
      .attr("stroke", colors[0]);

    //添加路径 -- 降雨
    svg.append("path")
      .data([renderRainData])
      .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
      .attr("d", function (d) {
        return rainLinePath(d);
      })
      .attr("fill", "none")
      .attr("stroke-width", 3)
      .attr("stroke", colors[1]);

    //x轴
    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom")
    //y轴 
    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    svg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(" + padding.left + "," + padding.top + ")")
      .call(yAxis);

    // 绘制图例
    var markStep = 80;
    var gMark = svg.selectAll(".gMark")
      .data([0, 1])
      .enter()
      .append("g")
      .attr("transform", function (d, i) {
        return "translate(" + (width - padding.left - 200 - i * markStep) + "," + (padding.top) + ")";
      });

    gMark.append("rect")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", 10)
      .attr("height", 10)
      .attr("fill", function (d, i) {
        return colors[i];
      });

    gMark.append("text")
      .attr("dx", 15)
      .attr("dy", ".5em")
      .attr("fill", "black")
      .text(function (d, i) {
        return i === 0 ? '产量' : '降雨量'
      });

    this.bindEvent(); // 图表绘制完成，绑定事件
  }
}